import axios from 'axios'
import { getToken } from '@/utils/auth'

/**
 * axios发送请求给后端下载Excel文件
 * @param {} apiUrl 路径
 */
export function exportExcel(apiUrl) {
  // 拼接URL
  const url = process.env.VUE_APP_BASE_API + apiUrl
  // 获取token
  const token = getToken()
  // 发送请求
  axios.get(url, {
    // 请求头信息 token
    headers: {
      'Authorization': token
    },
    // 二进制流
    responseType: 'blob'
  }).then(function(res) {
    if (!res) return
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
    const url = window.URL.createObjectURL(blob)
    const aLink = document.createElement('a')
    aLink.style.display = 'none'
    aLink.href = url
    aLink.setAttribute('download', 'data.xlsx')
    document.body.appendChild(aLink)
    aLink.click()
    document.body.removeChild(aLink)
    window.URL.revokeObjectURL(url)
  }).catch(function(error) {
    console.log(error)
  })
}
